import ModuleOffActivity from '@/components/ModuleActivity/ModuleOffActivity';
import ModuleGoods from '@/components/ModuleGoods';
import ModuleGoodsGroup from '@/components/ModuleGoodsGroup';
import ModuleImg from '@/components/ModuleImg';
import ModuleNav from '@/components/ModuleNav';
import ModuleNavBar from '@/components/ModuleNavBar';
import ModulePlace from '@/components/ModulePlace';
import ModuleProducts from '@/components/ModuleProducts';
import ModuleSearch from '@/components/ModuleSearch';
import ModuleShare from '@/components/ModuleShare';
import ModuleSlider from '@/components/ModuleSlider';
import ModuleStoreHead from '@/components/ModuleStoreHead';
import ModuleStoreNotice from '@/components/ModuleStoreNotice';
import ModuleText from '@/components/ModuleText';
import ModuleTitle from '@/components/ModuleTitle';
import { customeAppId } from '@/src/config';
import utils from '@/utils';
import { transform2px } from '@/utils/customModule';
import { debounce } from '@/utils/helper';
import { Image, ScrollView, View } from '@tarojs/components';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import Taro, { useDidShow } from '@tarojs/taro';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { EventNames, useEventCenterOn } from '../../dataTransfer/eventCenter';
import { TopCustomNavBarTopStyle } from '../ModuleNavBar/constants';
import './index.scss';

const noPageImgUrl = `https://ht-finesdk.oss-cn-beijing.aliyuncs.com/weapp/taihujishi/media/no-page.png`;

const ComponentsList = {
  ModuleSearch,
  ModuleTitle,
  ModuleImg,
  ModuleShare,
  ModuleNav,
  ModuleGoods,
  ModuleSlider,
  ModuleText,
  ModulePlace,
  ModuleProducts,
  ModuleGoodsGroup,
  ModuleStoreNotice,
  ModuleStoreHead,
  ModuleOffActivity,
};

function getContentTop(config) {
  const isImmerse =
    config?.topCustomNavBar?.styleSetting?.topStyle === TopCustomNavBarTopStyle.immerse;

  // 沉浸标题
  if (isImmerse) {
    return {};
  }
  return {
    height: utils.getCalcHeight({}, Taro.$statusBarHeight + 'px', Taro.$titleHeight + 'px'),
  };
}

const GetPageComponents = ({
  dispatch,
  customPageConfigPages,
  customePageName,
  pageName,
  isPreview,
  loading,
}) => {
  const [pageComponents, setPageComponents] = useState([]);
  const [scrollTop, setScrollTop] = useState(0);

  const config = customPageConfigPages?.[pageName] ?? {};
  // 避免默认的报错页面闪一下
  const [loaded, setLoaded] = useState(false);
  const [showNavbar, setshowNavbar] = useState(true)

  useEffect(() => {
    getPageConfig();
  }, []);
  useDidShow(()=>{
    if(Taro.getCurrentInstance().router.path == '/pages/mainPages/tabsPage/index'){
      setshowNavbar(false)
    }
  })

  useEffect(() => {
    if (config?.fields?.length > 0 && customePageName == pageName) {
      addPXforSize();
      generatePageComponents();
    }
    if (config?.title) {
      utils.setTitle(config.title);
    }
  }, [config]);

  const isLoading = useShowLoading(loading, [
    'otherApi/getCustomePreviewPageConfig',
    'otherApi/getCustomePageConfig',
  ]);

  const getPageConfig = () => {
    setTimeout(() => {
      setLoaded(true);
    }, 500);
    if (isPreview) {
      dispatch({
        type: 'otherApi/getCustomePreviewPageConfig',
        payload: {
          reviewId: pageName,
          pageName,
        },
      });
    } else {
      dispatch({
        type: 'otherApi/getCustomePageConfig',
        payload: {
          merchantId: customeAppId,
          pageName,
        },
      });
    }
  };

  const addPXforSize = () => {
    let sizeKeys = ['margin', 'padding', 'width', 'height', 'borderRadius'];
    for (let f = 0; f < config.fields.length; f++) {
      let styleSettingRender = config.fields[f].__slot__.styleSettingRender;

      for (let key in styleSettingRender) {
        for (let sk = 0; sk < sizeKeys.length; sk++) {
          if (key.toLowerCase().indexOf(sizeKeys[sk].toLowerCase()) >= 0) {
            if (
              typeof styleSettingRender[key] === 'number' &&
              !Number.isNaN(styleSettingRender[key]) &&
              styleSettingRender[key] > 0
            ) {
              // 保存下原有值, 防止后面可能会使用到
              styleSettingRender.__origin__ = {
                ...styleSettingRender.__origin__,
                [key]: styleSettingRender[key],
              };

              styleSettingRender[key] = transform2px(styleSettingRender[key]);
            }
          }
        }
      }
    }
  };

  const getComponent = (field, isLast) => {
    let Comp = ComponentsList[field.__slot__.moduleSign];

    if (!Comp) {
      console.error(`no module  "${field.__slot__.moduleSign}"  found, skip render`, field);
      return null;
    }

    return <Comp componentCfg={field.__slot__} pageName={pageName} isLast={isLast} />;
  };
  const generatePageComponents = () => {
    let pageComponentsList =
      config?.fields?.length > 0 &&
      config.fields.map((field, index) => {
        return getComponent(field, index === config.fields.length - 1);
      });
    setPageComponents(pageComponentsList);
  };

  const handleScrollToLower = debounce((e) => {
    Taro.eventCenter.trigger(EventNames.ModuleScrollToLower, {
      event: e,
      pageName,
      when: Date.now(),
    });
  }, 500);

  const handleScroll = (e) => {
    Taro.eventCenter.trigger(EventNames.ModuleScroll, {
      event: e,
      pageName,
    });
  };

  let bottomHight = Taro.$bottomHight;
  if (pageName == 'home') {
    if (Taro.$isH5 && window.history.length == 1 && Taro.$isIphoneX) {
      bottomHight = 2;
    } else if (!Taro.$isH5 && Taro.$isIphoneX) {
      bottomHight = 2;
    } else {
      bottomHight = 1;
    }
  } else {
    bottomHight = 0;
  }

  let bgStyle = {};
  if (config?.bgType) {
    bgStyle =
      config?.bgType == 2 ? {
        backgroundImage: `url(${config.bgImg})`,
        backgroundRepeat:'no-repeat',
        backgroundSize:'cover',
      } : config?.bgType == 3?  {
        background: `linear-gradient(180deg,${config.bgColor1}, ${config.bgColor2}) no-repeat`,
        backgroundSize:'100% 250PX'
      } : {
        backgroundColor: config.bgColor,
      }
  }

  const navTopStyle = useMemo(() => {
    return getContentTop(config);
  }, [config]);

  console.log('debug for getComponent', { pageName, config });

  const scrollToPosition = useCallback(
    (value = 0) => {
      if (scrollTop === value) {
        setScrollTop(value + Number.EPSILON);
      } else {
        setScrollTop(value);
      }
    },
    [scrollTop],
  );

  // 顶部双击监听
  useEventCenterOn(
    EventNames.ModuleNavBarDbClick,
    ({ event, pageName: dbClickPageName, from, position }) => {
      // 不是同一个页面
      if (dbClickPageName !== pageName) {
        return;
      }

      console.log('debug for dbClick', { from, position, dbClickPageName, event, scrollTop });

      scrollToPosition(0);
    },
    [scrollToPosition],
  );

  //  回到顶部监听
  useEventCenterOn(
    EventNames.SetModuleScroll,
    ({ pageName: pn, value }) => {
      // 不是同一个页面
      if (pn !== pageName) {
        return;
      }

      scrollToPosition(value);
    },
    [scrollToPosition],
  );

  if (loaded && !isLoading && !config?.title) {
    return (
      <view className="undefined-page">
        <ModuleNavBar
          title="页面不存在"
          pageName={pageName}
          componentCfg={config?.topCustomNavBar}
        />
        <view className="info-inner">
          <Image className="nextImg" src={noPageImgUrl} />
          <view className="text">页面不存在</view>
        </view>
      </view>
    );
  }

  return (
    <View style={{
      ...bgStyle
    }}>
      {config?.pageShareInfo && (
        <ModuleShare
          componentCfg={{
            content: config.pageShareInfo,
          }}
        />
      )}
      {showNavbar?
      <ModuleNavBar
        title={config?.title}
        pageName={pageName}
        componentCfg={config?.topCustomNavBar}
      />:null}

      <ScrollView style={{
        ...navTopStyle,
        padding:config?.margin>0?config?.margin+'PX':0
      }}
        className='customeContentPage'
        scrollY
        scrollTop={scrollTop}
        onScroll={handleScroll}
        onScrollToLower={handleScrollToLower}
        // 一个商品组件的高度
        lowerThreshold={utils.getSizeByScale(520)}
        scrollWithAnimation
        enableBackToTop
      >
        {pageComponents}
      </ScrollView>
    </View>
  );
};

export default connect(({ otherApi, loading }) => ({
  loading,
  config: otherApi.customePageConfig,
  customePageName: otherApi.customePageName,
  customPageConfigPages: otherApi.customPageConfigPages,
}))(GetPageComponents);
